package com.functest.orm

import groovy.sql.Sql

/**
 * @author: DavydovMD
 * Date: 11.04.13
 * Time: 14:24
 */

class MultiTableMapper<T> extends MultiMapper {
    Class<T> beanClass
    protected Map<SingleDbTableMapper, MapperBinding> mapperBindings = [:]
    protected Map<String, Closure<Sql>> databases = [:] //url -> database
    protected Map<String, Set<SingleDbTableMapper>> mappersPerUrl = [:] //url -> mappers

    MultiTableMapper(List<SingleDbTableMapper> mappers, Class beanClass, List<MapperBinding> bindings = []) {
        super(mappers as List<Mapper>)
        this.beanClass = beanClass

        bindings.each {
            mapperBindings.put it.mapper as SingleDbTableMapper, it
            if (it.mapper == mappers.get(0)) {
                throw new UnsupportedOperationException('Using binding for main mapper is NOT supported (yet)! Sorry!')
            }
        }

        mappers.each { SingleDbTableMapper mapper ->
            if (bindings.grep { MapperBinding binding ->
                binding.mapper == mapper }.empty) {
                mapperBindings.put mapper, new MapperBinding(mapper)
            }
            String url = mapper.dbUrl
            if (!mappersPerUrl.containsKey(url)) {
                mappersPerUrl.put(url, new HashSet([mapper]))
                databases.put(url, mapper.dbGetter)
            } else {
                mappersPerUrl.get(url).add(mapper)
            }
        }
    }

    @Override
    List<SingleDbTableMapper> getMappers() {
        super.mappers as List<SingleDbTableMapper>
    }


    Map<String, Set<SingleDbTableMapper>> getDbMappers() {
        mappersPerUrl
    }

    @Override
    SingleDbTableMapper findMapper(String field) {
        super.findMapper(field) as SingleDbTableMapper
    }

    MapperBinding getBinding(SingleDbTableMapper mapper) {
        mapperBindings.get(mapper)
    }


    QueryBuilder queryBuilder() {
        new SingleDbQueryBuilder(this)
    }
}
